<template>
  <div class="container">
    <el-card>

      <PageTools>
        <template v-slot:before>
          <el-button v-if="checkPerm('addagents')" type="primary" size="small" @click="addAgents">添加经纪</el-button>
        </template>

        <template v-slot:after>
          <slot name="after">

            <el-input v-model="input" placeholder="请输入关键字" />

            <el-button @click="screenAgent">筛选</el-button>

          </slot>
        </template>

      </PageTools>

      <!-- 表格 -->
      <el-table
        :data="tableData"
        style="width: 100%"
        border
      >
        <el-table-column
          prop="image"
          label="图片"
          width="180"
        >
          <!-- 图片数据上传完成 还需要进行图片显示 -->
          <template v-slot="{row}">
            <el-image :src="row.image" size="100px" alt="" />
          </template>

        </el-table-column>

        <el-table-column
          prop="name"
          label="名称"
          width="120"
        />
        <el-table-column
          prop="email"
          label="邮箱"
        />
        <el-table-column
          prop="phone"
          label="电话"
        />
        <el-table-column
          prop="address"
          label="地址"
        />
        <el-table-column
          prop="desc"
          label="描述"
          width="180"
        />
        <el-table-column
          prop="address"
          label="操作"
          width="145"
        >
          <template v-slot="{row}">

            <el-button v-if="checkPerm('editagents')" type="small" size="primary" @click="editFn(row)">编辑</el-button>
            <el-button v-if="checkPerm('delagents')" type="small" size="danger" @click="removeFn(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <hr>

      <el-row type="flex" justify="center">

        <!-- 分页器 -->
        <el-pagination
          layout="prev, pager, next"
          :total="total"
          :page-size="size"
          @current-change="changeStart"
        />
      </el-row>
    </el-card>

    <!-- 弹窗 -->
    <el-dialog
      :title="form.id?'编辑经纪人':'添加经纪人'"
      :visible="dialogShow"
      width="70%"
      @close="colse"
    >
      <el-form ref="form" label-width="120px" style="conter" :model="form" :rules="rules">
        <el-form-item prop="name" label="名称">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="form.address" />
        </el-form-item>
        <el-form-item prop="desc" label="描述">
          <el-input v-model="form.desc" type="textarea" />
        </el-form-item>
        <!-- 图片 -->
        <el-form-item label="封面">

          <el-upload
            action="#"
            :http-request="uploadFn"
            list-type="picture-card"
            :file-list="fileList"
            :limit="1"
            :on-remove="imgremove"
          >
            <i class="el-icon-plus" />
          </el-upload>
          <el-input placeholder="跳过图片强制上传" />
        </el-form-item>

        <el-form-item>
          <el-button type="small" size="danger" @click="colse">取消</el-button>
          <el-button type="small" size="primary" @click="addFn">确定</el-button>
        </el-form-item>

      </el-form>

    </el-dialog>
  </div>
</template>

<script>
import { getAgents, addAgents, getDesignee, updateAgent, deleteAgent, screenAgent, pageCount } from '@/api/agents.js'
import COS from 'cos-js-sdk-v5'
// var COS = require('cos-js-sdk-v5')

// SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
var cos = new COS({
  SecretId: 'AKID82g3B3exzkuznKcBYfV3KJ2TdZFdjY7U',
  SecretKey: '94h4C3PXOxFMDn56qKXIn11kGZdQwCBu'
})

export default {
  data() {
    return {
      total: 0,
      limit: 3,
      start: 1,
      input: '',
      size: 5,
      page: 1,
      tableData: [],
      dialogShow: false,
      form: { name: '', desc: '', address: '', email: '', image: '', phone: '' },
      rules: { name: [{ required: true, message: '名称不能为空', trigger: 'blur' },
        { min: 1, max: 18, message: '请输入活动名称', trigger: 'blur' }],
      desc: [{ required: true, message: '描述不能为空', trigger: 'blur' },
        { min: 1, message: '请输入描述', trigger: 'blur' }] },
      // 图片回调函数的值
      fileList: [
        // { url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100' }
      ]

    }
  },
  created() {
    this.getAgents()
  },
  methods: {
    // 分页
    changeStart(val) {
      this.page = val
      // console.log(val)
      this.getAgents()
    },
    // 获取总条数
    async pageCount() {
      const res = await pageCount()
      // console.log(180, res)
      this.total = res.data
    },
    // 查询
    async  screenAgent() {
      const res = await screenAgent(this.input)
      // console.log(res)
      this.tableData = res.data
    },
    // 删除
    removeFn(id) {
      this.$confirm('确认删除吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        await deleteAgent(id)
        // if (this.total % this.limit === 0) {
        //   this.start = (this.start - 1) * this.limit
        //   this.getAgents()
        // }

        this.getAgents()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 添加数据 / 编辑
    async addFn() {
      // 校验
      await this.$refs.form.validate()
      if (this.form.id) {
        // 图片更新
        this.form.image = this.fileList[0].url
        // 数据更新
        await updateAgent(this.form)
      } else {
        this.form.image = this.fileList[0].url
        await addAgents(this.form)
        // if(this.total/this.limit)
        // console.log(Math.ceil(this.total / this.limit))
        const { data } = await pageCount()
        console.log(4444, this.start, data)
        console.log(Math.ceil(data / this.limit))
        this.start = Math.floor(data / this.limit) + 1
        this.start = Math.ceil(this.start / this.limit) + 2
        // console.log(3434, this.start)
      }

      this.getAgents()
      this.colse()
    },
    // 编辑弹窗  回显
    async editFn(data) {
      // console.log(data)
      this.dialogShow = true
      const res = await getDesignee(data)
      // this.form.image = res.data.image
      // console.log(res)
      // 重新把数据显示到弹窗中 需要给显示图片的路径定义一个（第0个）url
      this.fileList = [{ url: '' }]
      // 然后第0个对象中的路径接收 返回数据的图片路径
      this.fileList[0].url = res.data.image
      this.form = res.data
    },
    // 封装渲染函数  获取数据
    async getAgents() {
      // 获取当前页起始下标
      // this.start = (this.start - 1) * this.limit
      // console.log(5465465, this.start)
      // console.log(this.limit)
      const res = await getAgents({
        _limit: this.size,
        _start: (this.page - 1) * this.size
      })
      // console.log(res)
      this.tableData = res.data
      this.pageCount()
    },
    addAgents() {
      this.dialogShow = true
    },
    // 关闭窗口
    colse() {
      this.dialogShow = false
      this.form = { name: '', desc: '', address: '', email: '' }
      this.imgremove()
    },
    // 图片删除时事件的函数
    imgremove(file, fileList) {
      //  清空路径
      this.fileList = fileList || []
      console.log(261, this.fileList)
    },
    // 图片逻辑
    // 图片
    uploadFn(data) {
      // console.log(171, data)
      this.fileList.push({
        url: ''
      })
      // 图片上传
      cos.putObject({
        Bucket: 'shiz-1313461633', /* 必须 */
        Region: 'ap-guangzhou', /* 存储桶所在地域，必须字段 */
        Key: Date.now().toString(), /* 必须 */
        StorageClass: 'STANDARD',
        Body: data.file, // 上传文件对象x`
        onProgress: function(progressData) {
          console.log(JSON.stringify(progressData))
        }
      }, (err, data) => {
        console.log(281, this.fileList)
        console.log(184, data)
        // console.log(185, err)
        if (!err) {
          this.fileList[0].url = 'https://' + data.Location
        }
      })
    }

  }
}

</script>

<style lang="scss" scoped>

.el-card{
  margin-top: 20px;
  .row-top{
    margin-bottom: 20px;
  }
}

hr{
  margin: 30px 0;
}
// 图片框样式
::v-deep .avatar-uploader .el-upload {
    border: 1px dashed  #979494;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
 ::v-deep .avatar-uploader-icon {
    font-size: 28px;
    color: #c3c5c7;
    width: 158px;
    height: 158px;
    line-height: 158px;
    text-align: center;
  }
 ::v-deep .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
